var dao = require('./talk.dao.js');
var constants = require('./constants.js');

var getTimeLevel = function(cell, time) {
	var timepoint = cell.alive + constants.timepoint.POINT - time;
	
	if (timepoint < 0) timepoint = 0;
	
	return Math.ceil(timepoint / constants.timepoint.LEVEL);
};

exports.startJob = function(io) {
	var job = setInterval(function() {
		dao.find({}, null, null, function (cells) {
			cells.forEach(function (cell) {
				// if cell is not master, skip timepoint calculation
				if (!cell.isMaster()) {
					return;
				}
				
				var time = Number(new Date());
				var timelevel = getTimeLevel(cell, time);
				
				if (timelevel == 0) { 
					// degrade cell
					cell.degrade(function() {
						io.sockets.emit('cell', cell);
						
						// update adjacent cells
						var nears = cell.getNearCellIds();
						for (var i = 0; i < nears.length; i++) {
							dao.get(nears[i], function(near) {
								near.removeNeighbor(cell._id, function() {
									io.sockets.emit('cell', near);
								});
							});
						};
					});
				}
				
				if (getTimeLevel(cell, time - constants.timepoint.INC) || timelevel) {
					io.sockets.emit('timepoint', {
						_id: cell._id,
						timelevel: timelevel
					});
				}
			});
		});
	}, constants.timepoint.INTERVAL);
};